<?php

class FileUpload {

// file upload
    public static $maxsize = '1024000000';
    public static $extname = 'JPEG,JPG,GIF,PNG,jpeg,jpg,gif,png,doc,docx,odt,xls,xlsx,ods,ppt,pptx,odp,pdf,mov,AVI,rmvb,rm,FLV,mp4,3GP';
    public static $uploaddir = '';

    public static function setUploaddir($path, $file_dir) {
        $serverFilePath = $_SERVER["SCRIPT_FILENAME"];
        $doc_dir = strpos($serverFilePath, $path);
        $doc_dir = substr($serverFilePath, 0, $doc_dir);   //project root
        FileUpload::$uploaddir = $doc_dir;
        FileUpload::mkdir_r($doc_dir . $file_dir);
        return $doc_dir;
    }

    public static function checkFileExt($ext) {
        $re = "/$ext/i";
        preg_match($re, FileUpload::$extname, $matches);
        return count($matches) > 0;
    }

    

    public static function mkdir_r($dir, $rights = 0777) {
        if (!is_dir($dir)) {
            $dirs = explode('/', $dir);
            $dir2 = '';
            foreach ($dirs as $part) {
                $dir2.=$part . '/';
                if (!is_dir($dir2) && strlen($dir2) > 0) {
                    mkdir($dir2, 0777);
                }
            }
        }
    }

    public static function uploadSingle($name, $item, $flag = false, $uploadfile) {
        $result = array();
        $fname = $_FILES[$name]['name'];
        $maxsize = 8*1024*1024;
        //echo '<hr/>';
        //echo '<br/>this filename:'.$this->filename.',fname:'.$fname.'.......'.$this->checkFileExt($fname).'<br/>'; 
        $ext = substr(strrchr($fname, "."), 1);
        if (FileUpload::checkFileExt($ext) || $flag) {
            $fsize = $_FILES[$name]['size'];
            //echo 'single fsize:'.$fsize.'...max:'.$this->maxsize.', temp_name:'.$_FILES[$name]['tmp_name'].'<br/>'; 
            if ($fsize < $maxsize) {
                $tmpfile = $_FILES[$name]['tmp_name'];
                $newFileName = $item . '.' . $ext;
                //echo "uploadfile: $uploadfile =tmpfile:$tmpfile ".$fsize.",  <br/>".$uploadfile.'/'.$newFileName; 
                if (is_uploaded_file($tmpfile)) {
                    if (move_uploaded_file($tmpfile, $uploadfile . '/' . $newFileName)) {
                        //copy($tmpfile, $uploadfile . '/' . $newFileName);    //可以用time()來改檔案名字 
                        //unlink($tmpfile);  //刪除在temp的檔案
                        return $newFileName;
                    }
                } else {
                    return 'fileupload'; //file upload erroe
                }
            }//size end 
            else {
                $fsize = 1024 * 1024;
                return 'filesize'; //file size too big;
            }
        }//fname 
        else {
            return 'fileext';  //file ext error
        }
        return $newFileName;
    }

//end func uploadSingle 

    public static function uploadMulit($name, $item) { 
        $result = array();
        $file_result = '';
        $i = 0;
        foreach ($_FILES[$name]['name'] as $value) {
            $fname = $_FILES[$name]['name'][$i];
            //check 副档名
            $ext =strtolower(substr(strrchr($fname, "."), 1));
            if (!FileUpload::checkFileExt($ext)) {
                $result[$i]["msg"] = '副档名不符';  //file ext error
                $result[$i]["filename"] = $fname;
            } else {
                $fsize = $_FILES[$name]['size'][$i];
                // check size 
                if ($fsize > FileUpload::$maxsize) {
                    $result[$i]["msg"] = '档案太大'; //file size too big;
                    $result[$i]["filename"] = $fname;
                } else {
                    $tmpfile = $_FILES[$name]['tmp_name'][$i];
                    $newFileName = $item . $i . '.' . $ext;
            
                    if (is_uploaded_file($tmpfile)) {
                        if (move_uploaded_file($tmpfile, FileUpload::$uploaddir . $newFileName)) {
                            $result[$i]["filename"] = $newFileName;
                            $result[$i]["msg"] = "ok";
                            $result[$i]["type"] = $_FILES[$name]['type'][$i];
                            $result[$i]["realname"] = $fname;
                        }
                    } else {
                        $file_result = '上传失败'; //file upload erroe
                        $result[$i]["msg"] = $file_result;
                        $result[$i]["filename"] = $fname;
                        $result[$i]["realname"] = $fname;
                    }
                }
            }
            $i++;
        }
        return $result;
    }

//end func uploadMulit 
    public static function uploadcheck($name) {
        $result = array();
        $i = 0;
        $maxsize = 1024444;
        foreach ($_FILES[$name]['name'] as $value) {
            $fname = $_FILES[$name]['name'][$i];
            $ext = substr(strrchr($fname, "."), 1);
            if (FileUpload::checkFileExt($ext)) {
                $fsize = $_FILES[$name]['size'][$i];
                if ($fsize > $maxsize) {
                    //檔案超過1MB
                    $result[$i]["size_msg"] = '檔案超過1MB';
                }
            }//fname ,副檔名錯誤
            else {
                $result[$i]["msg"] = '副檔名錯誤';
            }

            $i++;
        }
        return $result;
    }

    /*
     * 生成缩略图 以寬為主 getProportionByWidth
     */

    public static function resizeImage($srcImageFile, $destImageFile, $width, $height) {
        echo '$srcImageFile$srcImageFile:' . $srcImageFile, ', $destImageFile:' . $destImageFile;
        $srcImage = FileUpload::imageCreateFromFile($srcImageFile);
        if (empty($srcImage))
            return false;

        $extName = FileUpload::getExtFileName($destImageFile);
        if (empty($extName))
            return false;

        $extName = strtolower($extName);
        if ($extName === 'jpg' || $extName === 'jpeg') {
            $type = IMAGETYPE_JPEG;
        } else if ($extName === 'gif') {
            $type = IMAGETYPE_GIF;
        } else if ($extName === 'png') {
            $type = IMAGETYPE_PNG;
        } else
            return false;

        $info = FileUpload::getProportionWH($srcImageFile, $width, $height);
        if ($info['w'] < $width && $info['h'] < $height)
            return;

        $width = $info['w'];
        $height = $info['h'];

        $destImage = imagecreatetruecolor($width, $height);
        imagefilledrectangle($destImage, 0, 0, $width, $height, imagecolorallocate($destImage, 255, 255, 255));
        imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0, $width, $height, imagesx($srcImage), imagesy($srcImage));
        return imagepng($destImage, $destImageFile, 2);
        switch ($type) {
            case IMAGETYPE_PNG:
                return imagepng($destImage, $destImageFile, 2);
            case IMAGETYPE_JPEG:
            case IMAGETYPE_JPEG2000:
            // return imagejpeg($destImage, $destImageFile, 100);
            case IMAGETYPE_GIF:
                return imagegif($destImage, $destImageFile);
        }
        return false;
    }

    public static function imageCreateFromFile($imgFile) {
        if (!file_exists($imgFile) || !is_readable($imgFile)) {
            return null;
        }

        $imgInfo = getimagesize($imgFile);
        if (empty($imgFile))
            return null;
        switch ($imgInfo[2]) {
            case IMAGETYPE_GIF:
                return imagecreatefromgif($imgFile);
            case IMAGETYPE_JPEG:
            case IMAGETYPE_JPEG2000:
                return imagecreatefromjpeg($imgFile);
            case IMAGETYPE_PNG:
                return imagecreatefrompng($imgFile);
        }
        return null;
    }

    public static function getExtFileName($fileName) {
        $lastDotPos = strrpos($fileName, '.');
        if ($lastDotPos === false) {
            return false;
        }
        return substr($fileName, $lastDotPos + 1);
    }

    //返回 等比例宽高度
    public static function getProportionWH($srcImageFile, $width, $height) {

        $return = array('w' => $width, 'h' => $height);

        $imginfo = getimagesize($srcImageFile);

        $localarr = explode('"', $imginfo[3]);

        $w = isset($localarr[1]) ? $localarr[1] : 0;
        $h = isset($localarr[3]) ? $localarr[3] : 0;

        if (!$w || !$h)
            return $return;

        if ($w < $width && $h < $height)
            return array('w' => $w, 'h' => $h);
        if ($width / $height > $w / $h) {//如果新的压缩比例显示我要比原有的 长宽比大 那么 我因为依据 高为基础
            $return['h'] = $height;

            $return['w'] = $w * $height / $h;
        } else {
            $return['h'] = $h * $width / $w;

            $return['w'] = $width;
        }

        return $return;
    }

    public static function outPutImg($imgpath) {
        # standard height & weight if not given
        if (!isset($maxX))
            $maxX = 100;
        if (!isset($maxY))
            $maxY = 75;

# colour- & textvalues
        $picBG = "0,0,0"; # RGB-value !
        $picFG = "104,104,104"; # RGB-value !
        $copyright = "stefan bechtold";
        $font = 1;

# minimal & maximum zoom
        $minZoom = 1; # per cent related on orginal (!=0)
        $maxZoom = 200; # per cent related on orginal (!=0)
# paths
        $imgpath = "userimages/"; # ending with "/" !
        $nopicurl = "images/nopic.jpg"; # starting in $imagepath!!!
        $nofileurl = "images/nofile.jpg"; # starting in $imagepath!!!

        if (!isset($image) || empty($image))
            $imageurl = $imgpath . $nopicurl;
        elseif (!file_exists($imgpath . trim($image)))
            $imageurl = $imgpath . $nofileurl;
        else
            $imageurl = $imgpath . trim($image);

# reading image
        $image = getImageSize($imageurl, $info); # $info, only to handle problems with earlier php versions...
        switch ($image[2]) {
            case 1:
                # GIF image
                $timg = imageCreateFromGIF($imageurl);
                break;
            case 2:
                # JPEG image
                $timg = imageCreateFromJPEG($imageurl);
                break;
            case 3:
                # PNG image
                $timg = imageCreateFromPNG($imageurl);
                break;
        }

# reading image sizes
        $imgX = $image[0];
        $imgY = $image[1];

# calculation zoom factor 
        $_X = $imgX / $maxX * 100;
        $_Y = $imgY / $maxY * 100;

# selecting correct zoom factor, so that the image always keeps in the given format
# no matter if it is more higher than wider or the other way around
        if ((100 - $_X) < (100 - $_Y))
            $_K = $_X;
        else
            $_K = $_Y;

# zoom check to the original
        if ($_K > 10000 / $minZoom)
            $_K = 10000 / $minZoom;
        if ($_K < 10000 / $maxZoom)
            $_K = 10000 / $maxZoom;

# calculate new image sizes
        $newX = $imgX / $_K * 100;
        $newY = $imgY / $_K * 100;

# set start positoin of the image
# always centered 
        $posX = ($maxX - $newX) / 2;
        $posY = ($maxY - $newY) / 2;

# creating new image with given sizes
        $imgh = imageCreateTrueColor($maxX, $maxY);
            
# create small copy of the image
        imageCopyResampled($imgh, $timg, $posX, $posY, 0, 0, $newX, $newY, $image[0], $image[1]);
            

# output
        switch ($image[2]) {
            case 1:
                # GIF image
                header("Content-type: image/gif");
                imageGIF($imgh);
            case 2:
                # JPEG image
                header("Content-type: image/jpeg");
                imageJPEG($imgh);
            case 3:
                # PNG image
                header("Content-type: image/png");
                imagePNG($imgh);
        }

# cleaning cache
        imageDestroy($timg);
        imageDestroy($imgh);
# standard height & weight if not given
        if (!isset($maxX))
            $maxX = 100;
        if (!isset($maxY))
            $maxY = 75;

# colour- & textvalues
        $picBG = "0,0,0"; # RGB-value !
        $picFG = "104,104,104"; # RGB-value !
        $copyright = "stefan bechtold";
        $font = 1;

# minimal & maximum zoom
        $minZoom = 1; # per cent related on orginal (!=0)
        $maxZoom = 200; # per cent related on orginal (!=0)
# paths
        $imgpath = "userimages/"; # ending with "/" !
        $nopicurl = "images/nopic.jpg"; # starting in $imagepath!!!
        $nofileurl = "images/nofile.jpg"; # starting in $imagepath!!!

        if (!isset($image) || empty($image))
            $imageurl = $imgpath . $nopicurl;
        elseif (!file_exists($imgpath . trim($image)))
            $imageurl = $imgpath . $nofileurl;
        else
            $imageurl = $imgpath . trim($image);

# reading image
        $image = getImageSize($imageurl, $info); # $info, only to handle problems with earlier php versions...
        switch ($image[2]) {
            case 1:
                # GIF image
                $timg = imageCreateFromGIF($imageurl);
                break;
            case 2:
                # JPEG image
                $timg = imageCreateFromJPEG($imageurl);
                break;
            case 3:
                # PNG image
                $timg = imageCreateFromPNG($imageurl);
                break;
        }

# reading image sizes
        $imgX = $image[0];
        $imgY = $image[1];

# calculation zoom factor 
        $_X = $imgX / $maxX * 100;
        $_Y = $imgY / $maxY * 100;

# selecting correct zoom factor, so that the image always keeps in the given format
# no matter if it is more higher than wider or the other way around
        if ((100 - $_X) < (100 - $_Y))
            $_K = $_X;
        else
            $_K = $_Y;

# zoom check to the original
        if ($_K > 10000 / $minZoom)
            $_K = 10000 / $minZoom;
        if ($_K < 10000 / $maxZoom)
            $_K = 10000 / $maxZoom;

# calculate new image sizes
        $newX = $imgX / $_K * 100;
        $newY = $imgY / $_K * 100;

# set start positoin of the image
# always centered 
        $posX = ($maxX - $newX) / 2;
        $posY = ($maxY - $newY) / 2;

# creating new image with given sizes
        $imgh = imageCreateTrueColor($maxX, $maxY);

# setting colours
        $cols = explode(",", $picBG);
        $bgcol = imageColorallocate($imgh, trim($cols[0]), trim($cols[1]), trim($cols[2]));
        $cols = explode(",", $picFG);
        $fgcol = imageColorallocate($imgh, trim($cols[0]), trim($cols[1]), trim($cols[2]));

# fill background
        imageFill($imgh, 0, 0, $bgcol);

# create small copy of the image
        imageCopyResampled($imgh, $timg, $posX, $posY, 0, 0, $newX, $newY, $image[0], $image[1]);

# writing copyright note
        imageStringUp($imgh, $font, $maxX - 9, $maxY - 3, $copyright, $fgcol);

# output
        switch ($image[2]) {
            case 1:
                # GIF image
                header("Content-type: image/gif");
                imageGIF($imgh);
            case 2:
                # JPEG image
                header("Content-type: image/jpeg");
                imageJPEG($imgh);
            case 3:
                # PNG image
                header("Content-type: image/png");
                imagePNG($imgh);
        }

# cleaning cache
        imageDestroy($timg);
        imageDestroy($imgh);
    }

}

?>